package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.exception.BusinessException;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : 黑渊白花
 * @ClassName ReportServiceImpl
 * @date : 2025/8/15 16:13
 * @Description
 */
@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }

        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnoverList.add(turnover);
        }

        String join1 = StringUtils.join(dateList, ",");
        String join2 = StringUtils.join(turnoverList, ",");
        TurnoverReportVO build = TurnoverReportVO.builder()
                .dateList(join1)
                .turnoverList(join2)
                .build();

        return build;
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }

        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();

        // for (LocalDate date : dateList) {
        //     LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
        //     LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
        //     Map map = new HashMap();
        //     map.put("begin",beginTime);
        //     map.put("end",endTime);
        //     UserDate userDate = userMapper.sumUser(map);
        //     newUserList.add(userDate.getDailyNewUsers());
        //     totalUserList.add(userDate.getCumulativeUsers());
        // }
        List<UserDate> batchResults = userMapper.batchCountUserStats(dateList);
        for (UserDate batchResult : batchResults) {
            newUserList.add(batchResult.getDailyNewUsers());
            totalUserList.add(batchResult.getCumulativeUsers());
        }
        String join1 = StringUtils.join(dateList, ",");
        String join2 = StringUtils.join(newUserList, ",");
        String join3 = StringUtils.join(totalUserList, ",");
        return UserReportVO.builder()
                .dateList(join1)
                .newUserList(join2)
                .totalUserList(join3).build();
    }

    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        List<OrderDate> orderDates = orderMapper.batchCountOrderNumber(dateList);
        Integer totalOrderCount=0;
        Integer validOrderCount=0;
        List<Integer> newOrdersList = new ArrayList<>();
        List<Integer> effectiveList = new ArrayList<>();
        for (OrderDate orderDate : orderDates) {
            newOrdersList.add(orderDate.getDailyNewOrders());
            effectiveList.add(orderDate.getDailyEffectiveNewOrders());
            totalOrderCount+= orderDate.getDailyNewOrders();
            validOrderCount+= orderDate.getDailyEffectiveNewOrders();
        }
        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0 ){
            orderCompletionRate = validOrderCount/ (totalOrderCount*1.0);
        }

        String join1 = StringUtils.join(dateList, ",");
        String join2 = StringUtils.join(newOrdersList, ",");
        String join3 = StringUtils.join(effectiveList, ",");

        return OrderReportVO.builder()
                .dateList(join1)
                .validOrderCount(validOrderCount)
                .totalOrderCount(totalOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .validOrderCountList(join3)
                .orderCountList(join2)
                .build();
    }

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<SalesTop10> salesTop10 = orderMapper.getSalesTop10(beginTime,endTime);
        List<String> nameList = new ArrayList<>();
        List<String> countList = new ArrayList<>();
        for (SalesTop10 top10 : salesTop10) {
            nameList.add(top10.getName());
            countList.add(top10.getCount().toString());
        }
        String join1 = StringUtils.join(nameList, ",");
        String join2 = StringUtils.join(countList, ",");
        return SalesTop10ReportVO.builder()
                .nameList(join1)
                .numberList(join2)
                .build();
    }


    @Data
    static class DateRange {
        private final LocalDate begin;
        private final LocalDate end;
    }
    @Data
    public static class TurnoverDate {
        private LocalDate date;
        private Double totalAmount;
    }

    @Data
    public static class UserDate {
        private LocalDate date;
        private Integer dailyNewUsers;
        private Integer cumulativeUsers;
    }

    @Data
    public static class OrderDate {
        private LocalDate date;
        private Integer dailyNewOrders;
        private Integer dailyEffectiveNewOrders;
    }

    @Data
    public static class SalesTop10 {
        private String name;
        private Integer count;
    }

    private DateRange checkDate(LocalDate begin, LocalDate end) {
        if (begin == null && end == null) {
            throw new BusinessException("范围过大，请限定时间范围");
        }
        if (begin == null) {
            // 如果开始日期为空，默认按照end逆推30天
            begin = end.minusDays(29);
        }
        if (end == null) {
            // 如果开始日期为空，默认按照begin顺推30天
            end = begin.plusDays(29);
        }
        if (begin.isAfter(end)) {
            throw new BusinessException("时间选择错误");
        }
        if (ChronoUnit.DAYS.between(begin, end) > 30) {
            throw new BusinessException("时间超出30天，暂不支持查询");
        }
        return new DateRange(begin, end);
    }


}
